// src/minio/minio.service.ts
import { Injectable } from '@nestjs/common';
import * as Minio from 'minio';

@Injectable()
export class MinioService {
  private readonly minioClient: Minio.Client;
  private readonly bucketName: string;

  constructor() {
    // this.minioClient = new Minio.Client({
    //   endPoint: '192.168.203.128',
    //   port: 9001,
    //   useSSL: false,
    //   accessKey: 'c13HtgFPEpKZHbq5PL9X',
    //   secretKey: 'RYK8oLTWE9gZDmwre5Qis7iNkHbBY4Nc7Hhxb9gb',
    // });
    this.minioClient = new Minio.Client({
      endPoint: '192.168.203.128',
      port: 9001,
      useSSL: false,
      accessKey: 'IOlK2fElY7oNF2RSxtfF',
      secretKey: 'lvMzmwbNPFLP2SSY3gEpWzzXF8sf3bXVHrIPcD3Q',
    });
    this.bucketName = 'lzo-admin-nestjs-bucket';
  }

  // 确保存储桶存在
  async ensureBucketExists() {
    // 检查存储桶是否存在
    const exists = await this.minioClient.bucketExists(this.bucketName);
    // 如果存储桶不存在，则创建存储桶
    if (!exists) {
      await this.minioClient.makeBucket(this.bucketName, 'us-east-1');
    }
  }

  // 异步上传文件
  async uploadFile(file: Express.Multer.File, objectName?: string) {
    // 如果没有指定文件名，则使用当前时间戳和文件名拼接成新的文件名
    const fileName = objectName || `${Date.now()}-${file.originalname}`;
    // 使用minioClient上传文件
    await this.minioClient.putObject(
      this.bucketName,
      fileName,
      file.buffer,
      file.size,
      {
        // 设置文件类型
        'Content-Type': file.mimetype,
      },
    );
    // 返回文件名
    return fileName;
  }

  async getFileUrl(objectName: string, expiry = 24 * 60 * 60) {
    return await this.minioClient.presignedGetObject(
      this.bucketName,
      objectName,
      expiry,
    );
  }
}
